package com.junke.question.service.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.junke.question.service.entity.SysUser;
import com.junke.question.service.service.ISysUserService;
import com.junke.question.service.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 测试用的用户表 前端控制器
 * </p>
 *
 * @author whq
 * @since 2021-08-09
 */
@RestController
@RequestMapping("/auth")
public class SysUserController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;


    @Autowired
    AuthenticationManager authenticationManager;


    @Autowired
    JwtUtil jwtUtil;

    @PostMapping("/token")
    @ResponseBody
    public String findUser(@RequestBody SysUser user){
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassWord());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        return jwtUtil.createToken(user.getUserName());
    }


    @PostMapping("/create")
    @ResponseBody
    public String createUser(@RequestBody SysUser user){
        String passWord = bCryptPasswordEncoder.encode(user.getPassWord());
        user.setPassWord(passWord);
        boolean save = sysUserService.save(user);
        if(save){
            return "保存成功";
        }else{
            return "保存失败";
        }
    }

}
